package com.haoze.nurseapp.listen;

import com.alibaba.fastjson.JSON;
import com.haoze.common.constant.Constant;
import com.haoze.common.dto.OracleDcnDTO;
import com.haoze.common.enumeration.CirculationModelEnum;
import com.haoze.common.enumeration.CirculationTypeEnum;
import com.haoze.common.utils.JSONUtils;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.dao.CirculationLogMapper;
import com.haoze.nurseapp.dao.PatientInHospitalMapper;
import com.haoze.nurseapp.model.CirculationLogEntity;
import com.haoze.nurseapp.model.PatientInHospitalEntity;
import com.haoze.nurseapp.service.NurseTeamService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;


@Component
@ConditionalOnProperty(prefix = "kafkalistener", name = "openpatientdcn", havingValue = "true")
public class OracleDCNComponet {

    private static Logger logger = LoggerFactory.getLogger(OracleDCNComponet.class);

    @Resource
    private PatientInHospitalMapper patientInHospitalMapper;

    @Resource
    private CirculationLogMapper circulationLogMapper;

    @Autowired
    NurseTeamService nurseTeamService;

    @KafkaListener(topics = "${kafkatopic}", clientIdPrefix = "DCN")
    public void oracleDcn(ConsumerRecord<String, String> cr) {
//        logger.info("kafka新消息：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(cr));
        try {
            OracleDcnDTO oracleDcnDTO = JSON.parseObject(cr.value(), OracleDcnDTO.class);
            if (Constant.ORACLEDCN_PATIENT.equals(oracleDcnDTO.getTableName())) {
                //病人信息表
                if (Constant.METHOD_TYPE_INSERT.equals(oracleDcnDTO.getMethod())) {
//                    logger.info("新病人入院：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：rowId:{}",oracleDcnDTO.getRowId());
                    List<PatientInHospitalEntity> list = new CopyOnWriteArrayList<>();
                    try {
                        list.addAll(patientInHospitalMapper.findPatInfoByRowId(oracleDcnDTO.getRowId()));
                    } catch (Exception e) {
                        logger.error(e.getMessage() + "未找到指定记录ROWID：" + oracleDcnDTO.getRowId());
                    }
                    if (null != list && !list.isEmpty()) {
                        //表示有新病人入院
                        list.parallelStream().forEach(x -> {
                            List<CirculationLogEntity> cirList = circulationLogMapper.selectInHospLogByInpatNum(x.getInpatNum());
                            if(CollectionUtils.isEmpty(cirList)){
                                CirculationLogEntity circulationLogEntity = new CirculationLogEntity();
                                circulationLogEntity.setSourceType(Constant.SELF);
                                circulationLogEntity.setSerialNo(1);
                                circulationLogEntity.setPatTypeId(x.getPatTypeId());
                                circulationLogEntity.setInWardDeptId(x.getInWardDeptId());
                                circulationLogEntity.setInpatNum(x.getInpatNum());
                                circulationLogEntity.setInDoctorPersonId(x.getResponsibleDoctorPersonId());
                                circulationLogEntity.setInDeptId(x.getInDeptId());
                                circulationLogEntity.setHealthNum(x.getHealthNum());
                                circulationLogEntity.setCirculationOperateType(CirculationTypeEnum.IN_HOSP.getCode());
                                circulationLogEntity.setCirculationModelType(CirculationModelEnum.WAIT_IN_HOSP.getCode());
                                circulationLogEntity.setCirculationLogId(UUIDUtil.randomString());
                                circulationLogEntity.setStatus(0);
                                circulationLogEntity.initAdd();
                                circulationLogEntity.setBatchNo(1);
                                circulationLogMapper.insert(circulationLogEntity);
                            }
                        });
                    }
                }
            } else if (Constant.ORACLEDCN_CIRCULATIONLOG.equals(oracleDcnDTO.getTableName())) {
                //流转日志表
                if (Constant.METHOD_TYPE_INSERT.equals(oracleDcnDTO.getMethod())) {
//                    logger.info("新增流转日志：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：rowId:{}",oracleDcnDTO.getRowId());
                    List<CirculationLogEntity> list = new CopyOnWriteArrayList<>();
                    try {
                        list.addAll(circulationLogMapper.findCirculationLogByRowId(oracleDcnDTO.getRowId()));
                    } catch (Exception e) {
                        logger.error(e.getMessage() + "未找到指定记录ROWID：" + oracleDcnDTO.getRowId());
                    }
                    if (null != list && !list.isEmpty()) {
                        list.parallelStream().forEach(x -> {
                            Map<String, Object> map = new HashMap<>();
                            map.put("inpatNum", x.getInpatNum());
                            map.put("contentType", "text");
                            map.put("type", CirculationTypeEnum.getType(x.getCirculationOperateType()).getCode());
                            map.put("content", CirculationTypeEnum.getType(x.getCirculationOperateType()).getText());
                            nurseTeamService.saveMessage(map);
                        });
                    }
                }
            }
        } catch (Exception e) {
            logger.error("emr消息处理失败" + e.getMessage());
        }
    }
}
